﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using KMF.Common;
using KMF.DAL;
using KMF.Utility;
using KMF.WebUI.CustomHelpers;
using KMF.WebUI.Infrastructure;
using KMF.WebUI.Models;

namespace KMF.WebUI.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(CustomerLoginModel model)
        {
            var hasEmail = CustomerDb.GetByEmail(model.Email);
            if (hasEmail == null)
            {
                ModelState.AddModelError("error", "Không tồn tại email này!");
            }
            else
            {
                var password = model.Password.CreatePasswordHash(hasEmail.PasswordSalt);
                if (!password.Equals(hasEmail.Password))
                {
                    ModelState.AddModelError("error", "Mật khẩu không đúng!");
                }
                else
                {
                    var customerInfoLogin = new CustomerInfo
                    {
                        Address = hasEmail.Address,
                        BirthDay = hasEmail.Birthday,
                        CustomerId = hasEmail.Id,
                        DistrictId = hasEmail.DistrictId.ToString(),
                        DistrictName = hasEmail.DistrictName,
                        Email = hasEmail.Email,
                        FullName = hasEmail.FullName,
                        Gender = hasEmail.Gender,
                        MobilePhone = hasEmail.Mobilephone,
                        ProvinceId = hasEmail.ProvinceId.ToString(),
                        ProvinceName = hasEmail.ProvinceName,
                        Telephone = hasEmail.Telephone
                    };
                    Session[SessionConfig.SessionCustomerLogin] = customerInfoLogin;
                }
            }
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }
        public ActionResult Register()
        {
            var model = new CustomerRegisterModel();
            var provinceList = FunctionHelpers.GetProvinceList();
            provinceList.Insert(0, new ProvinceModel { ProvinceId = "", ProvinceName = "Tỉnh thành" });
            var districtList = new List<DistrictModel>();
            districtList.Insert(0, new DistrictModel { DistrictId = "", DistrictName = "Quận huyện" });

            model.ProvinceList = provinceList;
            model.DistrictList = districtList;

            var yearList = new List<YearModel>();
            for (var i = 1900; i <= 2013; i++)
            {
                yearList.Add(new YearModel { YearVal = i.ToString(), Year = i.ToString() });
            }
            yearList.Insert(0, new YearModel { YearVal = "", Year = "Năm" });
            model.YearList = yearList;

            var monthList = new List<MonthModel>();
            for (var i = 1; i <= 12; i++)
            {
                monthList.Add(new MonthModel { MonthVal = i.ToString(), Month = i.ToString() });
            }
            monthList.Insert(0, new MonthModel { MonthVal = "", Month = "Tháng" });
            model.MonthList = monthList;

            var dayList = new List<DayModel>();
            dayList.Insert(0, new DayModel { DayVal = "", Day = "Ngày" });
            model.DayList = dayList;

            model.Male = true;
            model.IsEmailMarketing = true;
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(CustomerRegisterModel model)
        {
            //Check email exists
            var hasEmail = CustomerDb.GetByEmail(model.Email);
            if(hasEmail != null)
            {
                var provinceList = FunctionHelpers.GetProvinceList();
                provinceList.Insert(0, new ProvinceModel { ProvinceId = "", ProvinceName = "Tỉnh thành" });
                var districtList = FunctionHelpers.GetDistrictList(int.Parse(string.IsNullOrEmpty(model.ProvinceId) ? "-1" : model.ProvinceId)) ?? new List<DistrictModel>();
                districtList.Insert(0, new DistrictModel { DistrictId = "", DistrictName = "Quận huyện" });

                model.ProvinceList = provinceList;
                model.DistrictList = districtList;

                var yearList = new List<YearModel>();
                for (var i = 1900; i <= 2013; i++)
                {
                    yearList.Add(new YearModel { YearVal = i.ToString(), Year = i.ToString() });
                }
                yearList.Insert(0, new YearModel { YearVal = "", Year = "Năm" });
                model.YearList = yearList;

                var monthList = new List<MonthModel>();
                for (var i = 1; i <= 12; i++)
                {
                    monthList.Add(new MonthModel { MonthVal = i.ToString(), Month = i.ToString() });
                }
                monthList.Insert(0, new MonthModel { MonthVal = "", Month = "Tháng" });
                model.MonthList = monthList;

                var dayList = new List<DayModel>();
                dayList.Insert(0, new DayModel { DayVal = "", Day = "Ngày" });
                model.DayList = dayList;

                TempData["HasEmail"] = "Email này đã tồn tại, bạn hãy nhập email khác!";
                return View(model);
            }

            if (ModelState.IsValid)
            {
                var passwordSalt = Guid.NewGuid().ToString();
                var password = model.Password.CreatePasswordHash(passwordSalt);
                var customerInfo = new CustomerDto
                {
                    Id = FunctionHelpers.GenerateId(),
                    FullName = model.FullName,
                    Password = password,
                    PasswordSalt = passwordSalt,
                    Email = model.Email,
                    Birthday = DateTime.Parse(model.Day + "/" + model.Month + "/" + model.Year),
                    Gender = model.Male ? "Nam" : "Nữ",
                    Address = model.Address,
                    Telephone = model.Telephone,
                    Mobilephone = model.MobilePhone,
                    ProvinceId = int.Parse(model.ProvinceId),
                    ProvinceName = model.ProvinceName,
                    DistrictId = int.Parse(model.DistrictId),
                    DistrictName = model.DistrictName,
                };
                if (CustomerDb.Add(customerInfo) > 0)
                {
                    customerInfo.EmailStatus = FunctionHelpers.SendMailRegisterSucccess(customerInfo.FullName, customerInfo.Email);
                    CustomerDb.Update(customerInfo);
                    var customerInfoLogin = new CustomerInfo
                    {
                        Address = customerInfo.Address,
                        BirthDay = customerInfo.Birthday,
                        CustomerId = customerInfo.Id,
                        DistrictId = customerInfo.DistrictId.ToString(),
                        DistrictName = customerInfo.DistrictName,
                        Email = customerInfo.Email,
                        FullName = customerInfo.FullName,
                        Gender = customerInfo.Gender,
                        MobilePhone = customerInfo.Mobilephone,
                        ProvinceId = customerInfo.ProvinceId.ToString(),
                        ProvinceName = customerInfo.ProvinceName,
                        Telephone = customerInfo.Telephone
                    };
                    Session[SessionConfig.SessionCustomerLogin] = customerInfoLogin;
                    return RedirectToAction("Index", "Home");
                }
            }

            return View(model);
        }

        public JsonResult GetDistrict(string provinceId)
        {
            var pId = string.IsNullOrEmpty(provinceId) ? "-1" : provinceId;
            var data = FunctionHelpers.GetDistrictList(int.Parse(pId)) ?? new List<DistrictModel>();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Logout()
        {
            Session[SessionConfig.SessionCustomerLogin] = null;
            return RedirectToAction("Index", "Home");
        }

        public PartialViewResult LoginOnProductDetail(string pId)
        {
            ViewBag.ProductId = pId;
            return PartialView();
        }

        [HttpPost]
        public JsonResult LoginOnProductDetail(CustomerLoginModel model)
        {
            var data = "0"; //dang nhap thanh cong
            var hasEmail = CustomerDb.GetByEmail(model.Email);
            if (hasEmail == null)
            {
                data = "1";//"Không tồn tại email này!";
            }
            else
            {
                var password = model.Password.CreatePasswordHash(hasEmail.PasswordSalt);
                if (!password.Equals(hasEmail.Password))
                {
                    data = "2";//"Mật khẩu không đúng!";
                }
                else
                {
                    var customerInfoLogin = new CustomerInfo
                    {
                        Address = hasEmail.Address,
                        BirthDay = hasEmail.Birthday,
                        CustomerId = hasEmail.Id,
                        DistrictId = hasEmail.DistrictId.ToString(),
                        DistrictName = hasEmail.DistrictName,
                        Email = hasEmail.Email,
                        FullName = hasEmail.FullName,
                        Gender = hasEmail.Gender,
                        MobilePhone = hasEmail.Mobilephone,
                        ProvinceId = hasEmail.ProvinceId.ToString(),
                        ProvinceName = hasEmail.ProvinceName,
                        Telephone = hasEmail.Telephone
                    };
                    Session[SessionConfig.SessionCustomerLogin] = customerInfoLogin;
                }
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}
